<template>
  <div id="manage">
    <!-- 左侧组织架构树 -->
    <div class="list-tree-area">
      <el-tree ref="tree" current-node-key='全部' :highlight-current='true' node-key="label" :default-expanded-keys="userOrgNodes" :data="userOrgNodes" :props="defaultProps" @node-click="handleNodeClick" :expand-on-click-node="false" :default-expand-all="defaultExpand"></el-tree>
    </div>

    <!-- 右侧用户管理列表 -->
    <div class="list-right-area">
      <!-- 检索条件 -->
      <div class="condition">
        <div class="firstInput">
          <p>关键字</p>
          <el-input size="small" class="input" placeholder="账号、昵称、手机号" v-model="searchParam.keyword"></el-input>
        </div>
        <el-button class="conditionBtn" size="small" type="primary" @click="curPage=1;refresh()" v-if="power.query">查询
        </el-button>
        <el-button class="conditionBtn" size="small" type="primary" :disabled="curOrgId=='all'" @click="isDisabled=false;addOrEditLoad($operType.add)" v-if="power.add">新增</el-button>
      </div>

      <!-- 用户列表 -->
      <el-table :data="tableData" stripe :max-height="tableMaxHeight" class="table">
        <el-table-column fixed prop="account" label="账号" header-align="center" width="100">
          <template slot-scope="scope">
            <el-link :underline="false" type="primary" @click="isDisabled = true;addOrEditLoad($operType.view,scope.row)">{{ scope.row.account }}</el-link>
          </template>
        </el-table-column>
        <el-table-column v-for="(column, index) in columns" :fixed="column.fixed" :prop="column.prop" :label="column.label" :min-width="column.width" header-align="center" :align="column.align" :key="index" :render="render">
          <template slot-scope="scope">
            <expand v-if="column.render!=null" :render="column.render" :row="scope.row" :index="index" :column="column"></expand>
            <span v-else>{{scope.row[column.prop]}}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button type="text" class="primaryTextBtn" @click="resetPwd(scope.row)" v-if="power.resetPwd">密码重置 </el-button>
            <el-button type="text" class="primaryTextBtn" :disabled="curOrgId=='all'" @click="isDisabled=false;addOrEditLoad($operType.update,scope.row)" v-if="power.update">修改</el-button>
            <el-button type="text" class="dangerTextBtn" :disabled="curOrgId=='all'" @click="deleteData(scope.row)" v-if="power.delete">冻结 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="page" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="curPage" :page-sizes="[10, 20]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="pageTotal"></el-pagination>
    </div>

    <!--新增编辑表单-->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" class="dialogForm" :title="title" v-if="dialogVisible" :visible.sync="dialogVisible" width="700px" :before-close="handleClose">
      <div class="line"></div>
      <el-form :ref="ref" :model="formParam" :rules="formParamRules" label-width="100px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户部门" prop="deptId">
              <!-- 添加时不允许修改单位信息，修改时允许进行修改 -->
              <el-select size="small" v-model="formParam.deptId" placeholder="请选择部门" :disabled="isDisabled || sendType==$operType.add.key">
                <el-option v-for="item in orgList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="用户名" prop="name">
              <el-input size="small" v-model="formParam.name" name="name" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="手机号" prop="phone">
              <el-input size="small" v-model="formParam.phone" name="phone" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="登陆账号" prop="account">
              <el-input size="small" v-model="formParam.account" name="account" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
          <!--   <el-col :span="11">
            <el-form-item label="">
               <el-upload class="avatar-uploader" action="https://jsonplaceholder.typicode.com/posts/" :show-file-list="false"
                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>  -->
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="微信" prop="wechat">
              <el-input size="small" v-model="formParam.wechat" name="wechat" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="邮件" prop="email">
              <el-input size="small" v-model="formParam.email" name="email" :disabled="isDisabled"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formParam.sex" name="sex" :disabled="isDisabled">
                <el-radio label="">未知</el-radio>
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="角色" prop="roles">
              <el-select size="small" multiple v-model="roles" placeholder="请选择角色" :disabled="isDisabled">
                <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="备注" prop="remark" size="small" style="width: 90%" :disabled="isDisabled">
            <el-input type="textarea" :rows="3" placeholder="请输入备注" v-model="formParam.remark" name="remark" :disabled="isDisabled">
            </el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="formBtn">
        <el-button size="small" type="primary" @click="addOrEditSubmit()" v-if="!isDisabled">确定</el-button>
        <el-button size="small" @click="cancel()" v-if="!isDisabled">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: "sysUser",
    inject: ["reload"],
    data() {
      var that = this;
      //查重
      let accountCheck = (rule, value, callback) => {
        var param = new FormData();
        param.append("account", value);
        if (that.formParam.id) param.append("id", that.formParam.id);
        that.$req.post(param, api.urlSysUserAccountCheck, function(_r) {
          if (_r.data) {
            callback(new Error(_r.message));
          } else {
            callback();
          }
        });
      };
      // 获取按钮权限
      let power = {
        query: this.$util.btnShow("sysUser.query"), //查询
        add: this.$util.btnShow("sysUser.add"), //新增
        update: this.$util.btnShow("sysUser.update"), //修改
        delete: this.$util.btnShow("sysUser.delete"), //删除
        resetPwd: this.$util.btnShow("sysUser.resetPwd"), // 重置密码
      }

      return {
        clientHeight: document.body.clientHeight, //窗口可视区域高度
        power: power, // 按钮显隐控制权限
        userOrgNodes: [{ id: 'all', label: '全部', type: "" }], //左侧父节点
        defaultProps: { children: "children", label: "label", id: "id", },
        curOrgId: "all", //当前选中的组织架构的id
        curOrgName: "全部", //当前选中的组织架构的名称
        defaultExpand: true, //默认展开所有节点

        roleList: [], // 角色列表
        // postList: [], // 岗位列表
        orgIdIsDisable: true, // 单位信息是否可以选择,默认不可选择

        orgList: [], // 部门的列表,默认是空
        userStatusShow: this.$storage.getDict("userStatus"),
        ref: "form",
        isDisabled: false, //表单是否可以编辑
        tableMaxHeight: 0, //表格的最大高度
        dialogVisible: false, //表单对话框显隐
        title: "",
        curPage: 1,
        pageSize: 10,
        pageTotal: 0,
        //搜索条件
        searchParam: { keyword: "" },
        // 新增，编辑 表单校验
        roles: [],
        formParamRules: {
          account: [{ required: true, message: "请填写登陆名，默认与手机号一致", trigger: "blur", }],
          name: [{ required: true, message: "请填写姓名", trigger: "blur" }, ],
          phone: [
            { required: true, pattern: that.$util.formRules.telPhone.regex, message: that.$util.formRules.telPhone.msg, trigger: "blur", },
            { validator: accountCheck, message: "手机号已存在", trigger: "blur" },
          ],
          deptId: [{ required: true, message: "请选择单位", trigger: "change" }],
        },
        sendType: "", //add 表示新增  edit 表示编辑 view 表示预览
        tableData: [],
        //表格列配置
        columns: [
          { fixed: false, prop: "name", align: "center", label: "姓名", width: "120", align: 'center' },
          { fixed: false, prop: "phone", align: "center", label: "手机号", width: "120", align: 'left' },
          {
            fixed: false,
            prop: "deptId",
            align: "center",
            label: "部门",
            width: "150",
            align: 'center',
            render(h, param) {
              let deptName = that.orgList.map(function(org, i) {
                if (org.value == param.row.deptId) {
                  return org.label;
                }
              })
              return h("div", deptName);
            },
          // }, {
          //   fixed: false,
          //   prop: "post",
          //   align: "center",
          //   label: "岗位",
          //   width: "120",
          //   align: 'center',
          //   render(h, param) {
          //     let postName = that.postList.map(function(post, i) {
          //       if (post.value == param.row.post) {
          //         return post.label;
          //       }
          //     })
          //     return h("div", postName);
          //   }
          },
          { fixed: false, prop: "remark", align: "center", label: "备注", width: "-", align: 'left' },
        ],
        // 新增编辑弹出表单
        formParam: {
          id: "", // 主键
          account: "", // 用户帐号
          name: "", // 姓名
          photo: "", // 头像
          sex: "", // 性别
          wechat: "", // 微信
          phone: "", // 联系方式
          email: "", // 邮件
          birthday: "", // 生日
          deptId: "", // 部门
          post: "", // 岗位
          sortNum: "", // 排序码
          remark: "", // 备注
        },
        formParamDefault: {
          id: "",
          account: "", // 用户帐号
          name: "", // 姓名
          photo: "", // 头像
          sex: "", // 性别
          wechat: "", // 微信
          phone: "", // 联系方式
          email: "", // 邮件
          birthday: "", // 生日
          deptId: "", // 部门
          post: "", // 岗位
          sortNum: "", // 排序码
          remark: "", // 备注
        },
      };
    },
    mounted() {
      var that = this;
      if (window.screen.height == 1080) {
        this.pageSize = 20;
      } else {
        this.pageSize = 10;
      }
      this.initOrgTree();
      this.getselectList();

      this.$nextTick(function() {
        //设置表格的最大高度
        setTimeout(function() {
          that.tableMaxHeight = that.$util.setTableMaxHeight();
        }, 500);
      });
      window.onresize = () => {
        return (() => {
          window.clientHeight = document.body.clientHeight;
          that.clientHeight = window.clientHeight;
        })();
      };
    },
    watch: {
      clientHeight(val) {
        let that = this;
        setTimeout(function() {
          that.$nextTick(function() {
            heightSet();
            that.tableMaxHeight = that.$util.setTableMaxHeight();
          });
        }, 500);
      },
      "formParam.phone"(newVal, oldVal) {
        if (this.formParam.account == oldVal) {
          this.formParam.account = newVal;
        }
      },
    },
    methods: {
      //左侧树点击事件
      handleNodeClick(data) {
        this.curOrgId = data.id;
        this.curOrgName = data.label;
        this.curPage = 1;

        this.refresh();
      },
      handleClose(done) {
        done();
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.refresh();
      },
      handleCurrentChange(val) {
        this.curPage = val;
        this.refresh();
      },
      // 获取左侧组织树
      initOrgTree() {
        let that = this;

        this.$req.get({}, api.urlSysOrganizeTree, function(_r) {
          that.userOrgNodes = that.userOrgNodes.concat(_r.data);

          that.refresh();
        });
      },
      refresh() {
        //查询
        let that = this;
        var param = new FormData();
        param.append("curPage", this.curPage);
        param.append("pageSize", this.pageSize);
        if (this.curOrgId != 'all') { // 如果是全部，则查看全部的
          param.append("deptId", this.curOrgId);
        }
        param.append("keyword", this.searchParam.keyword);
        this.$req.get(param, api.urlSysUserPage, function(_r) {
          that.tableData = _r.data.records;
          that.pageTotal = _r.data.total;
        });
      },
      getselectList() {
        let that = this;
        //角色list查询
        this.$req.get({ type: that.$constant.roleType.role }, api.urlSysRoleSelect, function(_r) {
          that.roleList = _r.data;
        });
        // //岗位的list信息
        // this.$req.get({ type: that.$constant.roleType.post }, api.urlSysRoleSelect, function(_r) {
        //   that.postList = _r.data;
        // });
        // 默认单位列表信息
        this.$req.get({}, api.urlSysOrganizeSelect, function(_r) {
          that.orgList = _r.data;
        });
      },
      // 删除
      deleteData(row) {
        let that = this;
        this.$util.msgbox.confrim("是否冻结改用户，用户冻结后将无法恢复?", function() {
          let param = new FormData();
          param.append("id", row.id);
          that.$req.post(param, api.urlSysUserLogicDelete, function(_r) {
            that.$util.notify.success("冻结成功");
            that.refresh();
          });
        });
      },
      /**
       * 表单提交前的逻辑判断及赋值，根据 sendType 来判断是新增还是编辑  add表示新增edit 表示编辑
       */
      addOrEditSubmit() {
        var that = this;
        var param = this.$util.formData(this.formParam, this.formParamDefault, "deptId");
        param.append("deptId", that.formParam.deptId); // 单位ID
        param.append("roleIds", that.roles); // 角色

        var url = "";
        if (this.sendType == this.$operType.add.key) {
          url = api.urlSysUserAdd;
        } else {
          url = api.urlSysUserUpdate;
        }

        that.$req.postForm(that.$refs[that.ref], param, url, function(_r) {
          let msg = "操作成功！";
          if (that.sendType == that.$operType.add.key) {
            msg += "默认密码为: " + _r.msg;
            that.$util.msgbox.success(msg);
          } else {
            that.$util.notify.success(msg);
          }
          that.$util.msgbox.success(msg);
          that.dialogVisible = false;
          that.refresh();
        });
      },
      /**
       * 添加或者编辑表单加载
       */
      addOrEditLoad(operType, row) {
        var that = this;

        this.dialogVisible = true;
        this.title = "账号信息" + operType.text;
        this.sendType = operType.key;

        if (operType.key == this.$operType.add.key) {
          this.formParam = this.$util.clone_str(this.formParamDefault);
          this.formParam.deptId = that.curOrgId.toString();
        } else {
          var formParam = that.$util.clone_str(row);
          formParam.deptId = formParam.deptId && formParam.deptId.toString();

          // 获取当前用户的id信息
          that.$req.get({ userId: formParam.id }, api.urlSysUserRoleList, function(_r) {
            that.roles = _r.data;
          });

          this.formParam = formParam;
        }
      },
      //重置密码
      resetPwd(row) {
        let that = this;
        this.$util.msgbox.confrim("是否重置密码?", function() {
          that.$req.post({ id: row.id }, api.urlSysUserResetPwd, function(_r) {
            that.$util.msgbox.success("密码重置为: " + _r.msg);
          });
        });
      },
      // 取消
      cancel() {
        this.dialogVisible = false;
      },
    },
  };
</script>

<style scoped lang='scss'>
  #manage {
    @include routerView;
  }

  .list-tree-area {
    width: 20%;
    padding: 0 1% 1% 1%;
    float: left;
    height: 100%;
    overflow-y: scroll;
  }

  .list-right-area {
    position: relative;
    width: 78%;
    margin-left: 22%;
    height: 100%;
  }

  .firstInput {
    @include inputLocation(240px);
  }

  .table {
    @include table;
  }

  .page {
    @include page;
  }

  .condition {
    @include condition;
  }

  .formBtn {
    @include formBtn;
  }

  .line {
    @include line;
  }

  .conditionBtn {
    @include conditionBtn;
    margin-top: 0px !important;
  }
</style>
<style lang='scss'>
  .dialogForm {
    @include dialogForm;
  }

  .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content {
    color: #409eff;
    font-weight: bold;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>